package com.ops.chirpit;

import java.util.HashMap;
import java.util.Map;

import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import org.json.JSONObject;

import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;


import fi.foyt.foursquare.api.FoursquareApi;
import fi.foyt.foursquare.api.FoursquareApiException;
import fi.foyt.foursquare.api.entities.CompleteUser;

public class AuthActivity extends Activity {
		protected static final String TAG = "ChirpIt";
		public static Map<String, String> prefs = new HashMap<String, String>();
	    final static String fsClientID = "ZBPIM302DKVCPBY1PMTAAJBRFPN2CAVOT4EDW0ZH3EVFIZ2A";
	    final static String fsClientSecret = "BDJYDG340AJUKTUINLQRTYR2DHP5QOCQLKTLWXLKFLYWMHW2";
	    static final String fsCallBackURL = "fs:///4sq";
        static String fsAuth_url = "https://foursquare.com/oauth2/authenticate" + 
                        "?client_id=" + fsClientID + 
                        "&response_type=token" + 
                        "&redirect_uri=" + fsCallBackURL;
        static String accessToken = null;

        private static final String[] PERMISSIONS =
            new String[] {"publish_stream", "read_stream", "offline_access", "manage_pages", "read_friendlists", "user_checkins", "publish_checkins"};
        private static String fbToken;
        private static String fbExpiry;
    	public final static String twConsumerKey = "cOmJnUixYm6ApJRYAJXyMQ";
    	public final static String twConsumerSecret = "Gwc1304Gs8Q8IgirASUns7QET2XBRzpjZYhVM9Ydlw";
    	private static CommonsHttpOAuthConsumer httpOauthConsumer = new CommonsHttpOAuthConsumer(twConsumerKey, twConsumerSecret);
    	private static OAuthProvider httpOauthprovider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
    			"http://twitter.com/oauth/access_token",
    			"http://twitter.com/oauth/authorize");
    	public static AccessToken a;
    	private final static String CALLBACKURL = "tw://twit";
    	private static String authUrl;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = this.getIntent();
        String request = intent.getData().toString().toLowerCase();
        int addAccountType = AccountType.getNameIndex(request);
        setContentView(R.layout.authenticate);

        addAccount(addAccountType);
    }
    
    public void addAccount(final int addAccountType) {
        switch(addAccountType){
        case 0:
    		try {
    			ChirpItActivity.twitter = new TwitterFactory().getInstance();
    			authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, CALLBACKURL);
            	WebView webview = (WebView)findViewById(R.id.authwebview);
    			webview.setPadding(20, 20, 20, 20);
    	        webview.getSettings().setJavaScriptEnabled(true);
    	        webview.setWebViewClient(new WebViewClient() {
    	            public void onPageStarted(WebView view, String url, Bitmap favicon) {
    	        		String message = null;
    	                String fragment = "oauth_verifier=";
    	                int start = url.indexOf(fragment);
    	                if (start > -1) {
    	                	if(a == null){
	    	                	//String token = "331980575-" + uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_TOKEN);
	    	                	Uri uri = Uri.parse(url.toString());
	    	        			String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
	    	        			try {
	    	        				String prefix = ChirpItActivity.accountTypes[addAccountType].prefix;
	    	        				// this will populate token and token_secret in consumer    	        			
	    	        				httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);    	        			
	    	        				// TODO: you might want to store token and token_secret in you app settings!!!!!!!!
	    	        				String token = httpOauthConsumer.getToken(), 
	    	        						secret = httpOauthConsumer.getTokenSecret(),
	    	        						id = token.substring(0, token.indexOf("-"));
	    	        				a = new AccessToken(token, secret);
	    	        				ChirpItActivity.twitter.setOAuthConsumer(twConsumerKey, twConsumerSecret);
	    	        				ChirpItActivity.twitter.setOAuthAccessToken(a);
	    	        				String name = ChirpItActivity.twitter.getScreenName();
	    	        				prefs.put(prefix + "_token_" + id, token);
	    	        				prefs.put(prefix + "_secret_" + id, secret);
	    	        				prefs.put(prefix + "_name_" + id, name);
	    	        				savePrefs();    	        			
	    	        				} catch (Exception e) {
	    	        				message = "e:" + e.getMessage();
	    	        				}
    	                	}
    	                }
    	            }
    	        });webview.loadUrl(authUrl);
    			} catch (Exception e) {
    			Toast.makeText(this, "e:" + e.getMessage(), Toast.LENGTH_LONG).show();
    		}
    		break;
        case 1:
        	ChirpItActivity.authenticatedFacebook.authorize(AuthActivity.this, PERMISSIONS,
                    new TestLoginListener());
        	break;
        case 2:
        	authUrl = fsAuth_url;
        	WebView webview = (WebView)findViewById(R.id.authwebview);
			webview.setPadding(20, 20, 20, 20);
	        webview.getSettings().setJavaScriptEnabled(true);
	        webview.setWebViewClient(new WebViewClient() {
	            public void onPageStarted(WebView view, String url, Bitmap favicon) {
	                String fragment = "#access_token=";
	                int start = url.indexOf(fragment);
	                if (start > -1) {
	                    // You can use the accessToken for api calls now.
	                    accessToken = url.substring(start + fragment.length(), url.length());
						ChirpItActivity.foursquareApi.setoAuthToken(accessToken);
	            	  	 String userID = null, userName = null;
						try {
							String prefix = ChirpItActivity.accountTypes[addAccountType].prefix;
							CompleteUser fsUser = ChirpItActivity.foursquareApi.user("self").getResult();
							userID = fsUser.getId();
							userName = fsUser.getFirstName() + " " + fsUser.getLastName();
	        				prefs.put(prefix + "_token_" + userID, accessToken);
	        				prefs.put(prefix + "_name_" + userID, userName);
						} catch (FoursquareApiException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	                     // ... and tada we have a authenticated Foursquare client
						savePrefs();
	                }
	            }
	        });
	        webview.loadUrl(authUrl);
	        break;
        }
      }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(resultCode == RESULT_OK){
    		Facebook authdFacebook = ChirpItActivity.authenticatedFacebook;
    		authdFacebook.authorizeCallback(requestCode, resultCode, data);
	        String fbToken = data.getStringExtra(authdFacebook.TOKEN);
	        String fbExpiry = data.getStringExtra(authdFacebook.EXPIRES);
	        try {
				String user = authdFacebook.request("me");
	            JSONObject obj = Util.parseJson(user);
	            String id = obj.getString("id");
	            String name = obj.getString("name");
		        prefs.clear();
		        prefs.put("fb_token_" + id, fbToken);
		        prefs.put("fb_secret_" + id, fbExpiry);
		        prefs.put("fb_name_" + id, name);
		        savePrefs();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}else
    		setResult(RESULT_CANCELED);
    		finish();
    }
    
    public static void authenticateFacebook(String token, String expiry){
    	fbToken = token;
    	fbExpiry = expiry;
    	ChirpItActivity.authenticatedFacebook.setAccessToken(fbToken);
    	ChirpItActivity.authenticatedFacebook.setAccessExpiresIn(fbExpiry);
    	
    }

	public static AccessToken authenticateTwitter(Uri uri) {
		String message = null;
		String tokens = null;
		if (uri != null && uri.toString().startsWith(CALLBACKURL)) {			
			//String token = "331980575-" + uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_TOKEN);
			String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
			try {
				// this will populate token and token_secret in consumer			
				httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);			
				// TODO: you might want to store token and token_secret in you app settings!!!!!!!!			
				a = new AccessToken(httpOauthConsumer.getToken(), httpOauthConsumer.getTokenSecret());	
				} catch (Exception e) {
				message = "e:" + e.getMessage();
				}
		}
		return a;
	}
	
    public void savePrefs(){
 		SharedPreferences sharedPrefs = getSharedPreferences(ChirpItActivity.ACCOUNT_PREFS, 0);
 		final Editor edit = sharedPrefs.edit();
 		for (String pref : prefs.keySet()){
 		  edit.putString(pref, prefs.get(pref));
 		}
 		edit.commit();
 		prefs.clear();
		Intent intent = new Intent(AuthActivity.this, ChirpItActivity.class);
    	intent.putExtra("ACTION", ChirpItActivity.ADD_ACCOUNT);
    	setResult(RESULT_OK, intent);
    	finish();
   }    

	public static FoursquareApi foursquareApi() {
		FoursquareApi foursquareApi = new FoursquareApi(fsClientID, fsClientSecret, fsCallBackURL);
		return foursquareApi;
	}

    public class TestLoginListener implements DialogListener {
        public void onComplete(Bundle values) {
            /*if (testAuthenticatedApi()) 
            } else {
            }
            if (testAuthenticatedErrors()) {
            } else {
            }*/
        }
        public void onCancel() {
    		setResult(RESULT_CANCELED);
        	finish();
        }
        public void onError(DialogError e) {
            e.printStackTrace();
        }
        public void onFacebookError(FacebookError e) {
            e.printStackTrace();
        }
    }

	public static JSONObject getFBPages() {
		// TODO Auto-generated method stub
		String user;
		JSONObject obj = null;
		try {
			user = ChirpItActivity.authenticatedFacebook.request("me/accounts");
			obj = Util.parseJson(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FacebookError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}
    
}